// Joost Vangoidsenhoven
#include "qtcardgroup.h"

QtCardGroup::QtCardGroup(QWidget *parent, Qt::WFlags flags): QWidget(parent, flags), columnSize(3)
{
	layout = new QGridLayout(this);
}

QtCardGroup::~QtCardGroup()
{
	Clear();
}

void QtCardGroup::SetSize(unsigned int size)
{
	Clear();

	for(unsigned int i=0; i<size; i++)
	{
		QtCard *card = new QtCard(this);

		QObject::connect(card, SIGNAL(ClickedCard(QtCard*)), this, SLOT(OnCardClicked(QtCard*)));

		unsigned int row = i / columnSize;
		unsigned int column = i % columnSize;
		
		layout->addWidget(card, row, column);

		cards.push_back(card);
	}
}


void QtCardGroup::Clear()
{
	std::vector<QtCard*>::iterator it;


	for(it = cards.begin(); it != cards.end(); ++it)
	{
		delete (*it);
	}

	cards.clear();
}

QtCard* QtCardGroup::GetCard(unsigned int index)
{
	if (index >= cards.size())
		throw "QtCardGroup: Could not get card, index out of bounds";

	return cards[index];
}

bool QtCardGroup::Full() const
{
	std::vector<QtCard*>::const_iterator it;


	for(it = cards.begin(); it != cards.end(); ++it)
	{
		if ( (*it)->IsEmpty())
			return false;
	}

	return true;
}


void QtCardGroup::RemoveCard(unsigned int index)
{
	if (index >= cards.size())
		throw "QtCardGroup: Cannot remove card, index out of bounds";

	cards[index]->SetEmpty();
}

unsigned int QtCardGroup::FirstEmptySlot() const
{
	unsigned int index = 0;
	std::vector<QtCard*>::const_iterator it;


	for(it = cards.begin(); it != cards.end(); ++it)
	{
		if ( (*it)->IsEmpty())
			return index;

		index++;
	}

	return -1;
}

void QtCardGroup::AddCard(const Card& card)
{
	if (Full())
		return;

	unsigned int index = FirstEmptySlot();

	if (index != -1)
	{
		cards[index]->SetCard(card);
	}
}



void QtCardGroup::SetColumnSize(unsigned int size)
{
	columnSize = size;
}

void QtCardGroup::SetCardGroup(const CardGroup& group)
{
	Clear();
	SetSize(group.Size());

	for(unsigned int i=0; i<group.Size(); i++)
	{
		AddCard(group.GetCard(i));
	}
}

bool QtCardGroup::Find(QtCard* card, unsigned int* index) const
{
	for(unsigned int i=0; i<cards.size(); i++)
	{
		if (cards[i] == card)
		{
			*index = i;
			return true;
		}
	}

	return false;
}



void QtCardGroup::OnCardClicked(QtCard* card)
{
	unsigned int index;

	if (Find(card, &index))
	{
		emit ClickedCard(this, index);
	}
}